<template>
    <el-container style="align-self: center;" >
        <el-aside style="padding-top: 20px;">
            <div v-for="item in data" :key="item.yourId">
                <div class="diaglog-div" :class="{ 'active': item.active }" @click="talk(item)">
                    <el-badge :value="item.unreadNum" class="item" v-if="item.unreadNum != 0">
                        <el-row>
                            <el-col :span="4">
                                <el-avatar :size="50" :src="getUserHeadIcon(item)"></el-avatar>
                            </el-col>
                            <el-col :span="18" :offset="2">
                                <div>{{ item.yourName }}</div>
                                <template v-if="item.draftInfo!=''">
                                    <div style="font-size: small;color: gray;text-align: start;">{{getMoment(new Date(item.draftTime)) }}</div>
                                <div
                                    style="width: 200px;font-size: small;color: chocolate;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                    <i class="el-icon-edit"></i>{{ item.draftInfo }}</div>
                                </template>
                                <template v-else>
                                    <div style="font-size: small;color: gray;text-align: start;">{{getMoment(new Date(item.chatTime)) }}</div>
                                <div
                                    style="width: 200px;font-size: small;color: gray;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                    {{ item.chatInfo }}</div>
                                </template>
                                
                            </el-col>
                        </el-row>
                    </el-badge>
                    <template v-else>
                        <el-row>
                            <el-col :span="4">
                                <el-avatar :size="50" :src="getUserHeadIcon(item)"></el-avatar>
                            </el-col>
                            <el-col :span="18" :offset="2">
                                <div>{{ item.yourName }}</div>
                                <template v-if="item.draftInfo!=''">
                                    <div style="font-size: small;color: gray;text-align: start;">{{getMoment(new Date(item.draftTime)) }}</div>
                                <div
                                    style="width: 200px;font-size: small;color: chocolate;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                    <i class="el-icon-edit"></i>{{ item.draftInfo }}</div>
                                </template>
                                <template v-else>
                                <div style="font-size: small;color: gray;text-align: start;">{{getMoment(new Date(item.chatTime)) }}</div>
                                <div
                                    style="width: 200px;font-size: small;color: gray;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                    {{ item.chatInfo }}</div>
                                </template>
                            </el-col>
                        </el-row>
                    </template>
                </div>
            </div>
        </el-aside>
        <el-main>
            <router-view @reload-event="reloadEvent" :sonData="sonData"></router-view>
        </el-main>

    </el-container>
</template>

<script>
import { getMsgs } from '@/api/chat';
import { getUserInfo } from '@/api/common';
import moment from 'moment';
import Vue from 'vue';

export default {
    data() {
        return {
            sonData:1,
            webSocket:null,
            // 渲染需要，一个临时容器
            chatData: null,
            // 联系人列表list
            data: []
        }
    },
    methods: {
    getMoment(time){
      const now=moment()
      const chatMoment=moment(time)
      if (chatMoment.isSame(now,'day')) {
        return `今天 ${chatMoment.format('HH:mm')}`
      }else if (chatMoment.isSame(now.clone().subtract(1,"day"),"day")) {
        return `昨天 ${chatMoment.format('HH:mm')}`
      }else{
        return chatMoment.format('YYYY-MM-DD-HH:mm')
      }
    },
        getUserHeadIcon(item){
      try {
        return require(`D:/staticFile/user${item.yourHeadIcon}`)
        
      } catch (error) {
        return item.headIcon;
      }
    },
        reloadEvent(){
            console.log("父组件回调");
            
        },
        // 点击联系人切换说话对象
        talk(item) {
            // 遍历把所有的激活状态改为false
            this.data.forEach(list => list.active = false)
            // 激活当前的
            item.active = true;
            this.chatData = item
            this.chatData.unreadNum = 0
            if (this.$route.path != `/main/interact/chatUser/${item.yourId}`) {
                this.$router.push(`/main/interact/chatUser/${item.yourId}`);
            }
            // this.startInterval()

        },
        // 刷新的初始化信息
        getPageInfo() {
            getMsgs({
                "role": "user",
                "myRole": "hr",
                "myId": this.$store.state.hrId
            }).then(res => {
                // res.data.forEach(item => {
                //     this.getInfo(item)
                // })
                //保留顺序
                res.data.forEach(item => {
                    if (item.yourId == this.chatData.yourId) {
                        this.chatData = item
                        item.active = true
                    }
                })
                 this.data = res.data

            })
        },
        // getInfo(item) {
        //     getUserInfo({ "userId": item.yourId }).then(res => {
        //         item.yourName = res.data.username;
        //         item.headIcon = res.data.headIcon;
        //         // item.isBlocked=res.data.isBlocked;
        //         // item.isCollected=res.data.isCollected
        //     })
        // }
    },
    mounted() {
        this.$store.dispatch("changeLoading",true);
        this.webSocket = new WebSocket(`ws://127.0.0.1:7060/ws?role=hr&id=${this.$store.state.hrId}`);
        // 后端socket发送消息的监听器
        this.webSocket.onmessage = (event)=> {
            this.getPageInfo()
            this.sonData++
        };
        // 这里为了子路由能用它的send方法，上传到vuex
        this.$store.dispatch("updateWebSocket",this.webSocket)

        // 初始化信息
        getMsgs({
            "role": "user",
            "myRole": "hr",
            "myId": this.$store.state.hrId
        }).then(res => {
            // 遍历去后端拿头像名字收藏未收藏等基础信息
            // res.data.forEach(item => {
            //     this.getInfo(item)
            // })
             this.data = res.data
            // 如果是通过简历对话跳转，则跳转对应位置
            if (localStorage.getItem("goTalkUser") != null) {
                const id = localStorage.getItem("goTalkUser")
                res.data.forEach(item => {
                    if (item.yourId == id) {
                        this.chatData = item
                        item.active = true
                        localStorage.removeItem("goTalkUser")
                    } else {
                        item.active = false
                    }
                })
            }
            // 正常菜单进入跳转到第一条
            else {
                // 正常菜单进入但是没有聊天过，就会返回空数组。这里非空判断避免渲染undified报错
                if (res.data.length != 0) {
                    this.talk(res.data[0])
                } else {
                    this.$message.error("您还没有发起过聊天")
                }

            }
            this.$store.dispatch("changeLoading",false);
        })

    },
    beforeDestroy() {
        // 销毁时websocket下线
        this.webSocket.close(1000, '正常关闭');
        // 把null的websocket同步到vuex。也就是把vuex的下线
        this.$store.dispatch("updateWebSocket")
    }

}
</script>

<style scope>
.diaglog-div {
    border-radius: 4px;
    padding: 20px;
    transition: 0.5s;
}

.diaglog-div:hover {
    background-color: #F1F2F3;
}

.active {
    background-color: #F1F2F3;
}
</style>